package com.daxia.ogmall.web.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.daxia.ogmall.common.DesignType;
import com.daxia.ogmall.common.ProductSellingStatus;
import com.daxia.ogmall.dto.DesignDTO;
import com.daxia.ogmall.dto.DesignProductDTO;
import com.daxia.ogmall.dto.SpecificationDTO;
import com.daxia.ogmall.dto.UserDTO;
import com.daxia.ogmall.model.Design;

@Controller
@RequestMapping(value = "plan", produces="text/html;charset=UTF-8")
public class PlanController extends BaseController {
	private static Logger logger = Logger.getLogger(PlanController.class);
	
	/**
	 * 三维家调用欧工b2b的接口，将方案信息传过来
	 * @param ogSessionId 用户从欧工b2b访问三维家时带过去的ogSessionId
	 * @param planId 设计方案在三维家这边的标识
	 * @param _3dUrl 设计方案的展示url
	 * @param images 设计方案各个空间截图的图片地址数组，用逗号隔开，比如http://xxx/1.jpg,http://xxx/2.jpg
	 * @param productCodes 方案对应的商品清单列表，用逗号隔开，比如og123,og456
	 * @param productCounts 方案对应的商品的数量，用逗号隔开，和productCodes的商品顺序一一对应，比如1,2，表示og123这个商品数量是1，og456这个商品数量是2
	 * @return
	 */
	@Transactional
	@ResponseBody
    @RequestMapping(value = "/save")
    public String save(String ogSessionId, String planId, @RequestParam("3dUrl") String _3dUrl, String images, 
    		String productCodes, String productCounts, String area,
    		String name) {
		logger.error("save plan, ogSessionId: " + ogSessionId + ", planId: " + planId + ", 3dUrl: " + _3dUrl 
				+ ", images: " + images + ", productCodes: " + productCodes + ", productCounts: "
				+ productCounts + ", area: " + area + ", name: " + name);
		assertTrue(StringUtils.isNotBlank(ogSessionId), "ogSessionId不能为空");
		assertTrue(StringUtils.isNotBlank(planId), "planId不能为空");
		//assertTrue(StringUtils.isNotBlank(_3dUrl), "3dUrl不能为空");
		assertTrue(StringUtils.isNotBlank(images), "images不能为空");
		if (StringUtils.isBlank(productCodes)) {
			return ok();
		}
		//assertTrue(StringUtils.isNotBlank(productCodes), "productCodes不能为空");
		//assertTrue(StringUtils.isNotBlank(productCounts), "productCounts不能为空");
		
		UserDTO user = userService.findByOgSessionId(ogSessionId);
		assertTrue(user != null, "ogSessionId不合法");
		
		{
			String[] specificationArr = productCodes.split(",");
			boolean hasProducts = false;
			for (String ogCode : specificationArr) {
				SpecificationDTO s = specificationService.findByOgCode(ogCode);
				if (s == null) {
					continue;
				}
				/*
				if (s.getProduct().getSellingStatus() == null || s.getProduct().getSellingStatus() != ProductSellingStatus.OnSell.getValue()) {
					logger.error("产品已下架【" + ogCode + "】");
					continue;
				} */
				if (s != null) {
					hasProducts = true;
					break;
				}
			}
			if (!hasProducts) {
				logger.error("没有包含欧工产品");
				return ok();
			}
		}
	
		// 1 保存到方案里
		boolean add = false;
		DesignDTO d = designService.findByPlanId(planId);
		if (d == null) {
			add = true;
			d = new DesignDTO();
		}
		
		d.setDesigner(designerService.findByUser(user.getId()));
		String[] imageArr = images.split(",");
		String details = "";
		for (String i : imageArr) {
			details += "<img src='" + i + "' style='width: 100%; margin-top: 10px;'/>";
		}
		//d.setDetails(details);
		d.setContent(details);
		d.setHeadImage(imageArr[0]);
		d.setImages(images);
		d.setTitle(name);
		d.setType(DesignType.Images.getValue());
		d.setUser(user);
		d.setView3dURL(_3dUrl);
		d.setPlanId(planId);
		d.setArea(area);
		/*
		 * 
		d.setArea(area);
		d.setCommunity(community);
		d.setCommunityHouseType(communityHouseType);
		d.setCompany(company);
		d.setContent(content);
		d.setHouseStyle(houseStyle);
		d.setHouseType(houseType);
		d.setId(id);
		d.setMaxArea(maxArea);
		d.setMinArea(minArea);
		d.setPdf(pdf);
		d.setPrice(price);
		d.setQRCode(qRCode);
		d.setTheme(theme);
		//d.setVRURL(vRURL);
		 */
		Long designId = null;
		if (add) {
			designId = designService.create(d);
		} else {
			designId = d.getId();
			designService.updateAllFields(d);
			
			designProductService.deleteByDesignId(designId);
		}

		int seq = 0;
		String[] specificationArr = productCodes.split(",");
		String[] countArr = productCounts.split(",");
		int i = 0;
		double totalPrice = 0d;
		for (String ogCode : specificationArr) {
			SpecificationDTO s = specificationService.findByOgCode(ogCode);
			int count = Integer.parseInt(countArr[i]);
			i ++;
			if (s == null) {
				continue;
			}
			totalPrice += s.getRealPrice();
			DesignProductDTO dp = new DesignProductDTO();
			dp.setDesign(new Design());
			dp.getDesign().setId(designId);
			
			dp.setProduct(s.getProduct());
			dp.setSpecification(s);
			dp.setCount(count);
			dp.setSeq(seq ++);
			designProductService.create(dp);
		}
		
		DesignDTO _d = designService.load(designId);
		_d.setPrice(totalPrice);
		designService.updateAllFields(_d);
		
		// 2 保存方案清单
		return ok();
    }

   
}	
